import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Date;


public class Upload {
    /**
     * 文件上传方法
     *
     * @param url 服务器地址
     * @param method 上传方式
     * @param filePath 本次上传文件的路径
     * @return 服务器返回的uuid（唯一标识）
     * @throws Exception
     */
    public String uploadFile(String url, String method, String filePath) throws Exception {

        URL connectionUrl = new URL(url);
        URLConnection urlConnection = connectionUrl.openConnection();
        HttpURLConnection connection = (HttpURLConnection) urlConnection;
        //将该连接的输入输出都设置为允许
        connection.setDoInput(true);
        connection.setDoOutput(true);
        if (method.equals("POST")) {
            connection.setUseCaches(false);
            connection.setRequestMethod("POST");
        } else {
            connection.setRequestMethod("GET");
        }
        //长连接,建议服务器端保留连接，这样下次向同一个服务器发请求时可以走同一个连接
        connection.setRequestProperty("Connection", "Keep-Alive");
        //设置请求编码格式
        connection.setRequestProperty("Charset", "UTF-8");
        //连接阶段的设置结束

        String fileType=filePath.substring(filePath.indexOf("."));
        File file=new File(filePath);
        if (!file.exists()){
            return "指定文件路径不存在";
        }
        connection.setRequestProperty("size", String.valueOf(file.length()));
        connection.setRequestProperty("type",fileType);
        connection.setRequestProperty("name", URLEncoder.encode(file.getName(), "UTF-8"));
        connection.setRequestProperty("time",new Date().toString());

        //将文件写入流中
        OutputStream os = new DataOutputStream(connection.getOutputStream());
        FileInputStream fs = new FileInputStream(filePath);
        byte[] b = new byte[2048];
        int length = 0;
        while ((length = fs.read(b)) != -1) {
            os.write(b, 0, length);
        }
        fs.close();
        os.flush();

        //获取服务端的响应
        InputStream is = connection.getInputStream();
        length=0;
        StringBuffer stringBuffer = new StringBuffer();
        while ((length = is.read()) != -1) {
            stringBuffer.append((char) length);
        }
        os.close();
        return stringBuffer.toString();
    }

}
